{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.59480768]\n",
      " [ 0.48813888]\n",
      " [ 0.32931632]\n",
      " [ 0.25304353]\n",
      " [ 0.41321605]\n",
      " [ 0.3163633 ]\n",
      " [ 0.23694597]\n",
      " [ 0.87413651]\n",
      " [ 0.71537739]\n",
      " [ 0.21074541]]\n"
     ]
    }
   ],
   "source": [
    "x =tf.placeholder(tf.float32,[None,1])\n",
    "y = 4*x+1\n",
    "\n",
    "#定义变量\n",
    "w = tf.Variable(tf.random_normal([1],-1,1))\n",
    "b = tf.Variable(tf.zeros(1))\n",
    "y_predict = w*x+b\n",
    "\n",
    "#loss\n",
    "loss = tf.reduce_mean(tf.square(y-y_predict))\n",
    "train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)\n",
    "\n",
    "isTrain = False\n",
    "train_steps = 250\n",
    "check_point_steps = 50\n",
    "checkpoint_dir = 'd:/tensorflow_study/rnn/'\n",
    "\n",
    "#保存model\n",
    "saver = tf.train.Saver()\n",
    "x_data = np.reshape(np.random.rand(10).astype(np.float32),(10,1))\n",
    "print(x)\n",
    "\n",
    "init = tf.global_variables_initializer()\n",
    "\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "    if isTrain:\n",
    "        for i in xrange(train_steps):\n",
    "            sess.run(train_step,feed_dict={x:x_data})\n",
    "            if (i+1) % check_point_steps==0:\n",
    "                saver.save(sess,checkpoint_dir+'model.ckpt',global_step=i+1)\n",
    "            print(sess.run(w))\n",
    "            print(sess.run(b))\n",
    "    else:\n",
    "        chpt = tf.train.checkpoint_state(checkpoint_dir)\n",
    "        if chpt and chpt.model_checkpoint_path:\n",
    "            saver.restore(sess,chpt.model_checkpoint_path)\n",
    "        else:\n",
    "            pass\n",
    "        print(sess.run(w))\n",
    "        print(sess.run(b))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
